import { Table, Button, Space, Popconfirm, Divider, Modal } from 'antd';
import jtsrc from './jt.png';
import jt2src from './jt-2.png';
import removeSrc from './remove.png';
import styles from './index.less';
import Title from './title';
import Homework from './homework/old-index';
import Chapter from './chapter';
import Type from './type';
import React, { useEffect, useState } from 'react';
import AddLesson from './add-lesson';
import { allGet, allPost } from '@/services/pc';
import { message } from 'antd';
import { useHistory } from 'umi';
import qs from 'qs';
import Empty from '@/pages/pc/components/Empty';
import { calcIndex } from '@/utils';
import classnames from 'classnames';

const sharedOnCell = (record: any) => {
  if (record.children) {
    return { colSpan: 0 };
  }

  return {};
};

const Index = ({ dataSource, reload, loading = true, isModal = false, ...props }) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>();
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>();

  const { classid = 0 /* 没有就是0，php认为是新增...*/ } =
    props.classid !== undefined ? props : (useHistory().location as any)?.query;
  const [data, setData] = useState(
    dataSource || [],
    // dataSource || [
    //   {
    //     title: 'Blender《大城市场景》创建流程教学【英音中字】',
    //     work: false,
    //     courseType: 1,
    //     id: 1,
    //     children: [
    //       {
    //         id: 2,
    //         title: 'Blender《大城市场景》创建流程教学【英音中字】',
    //         work: false,
    //         courseType: 1,
    //       },
    //       {
    //         id: 3,
    //         title: 'Blender《大城市场景》创建流程教学【英音中字】',
    //         work: false,
    //         courseType: 1,
    //       },
    //       {
    //         id: 4,
    //         title: 'Blender《大城市场景》创建流程教学【英音中字】',
    //         work: false,
    //         courseType: 1,
    //       },
    //     ],
    //   },
    //   {
    //     title: 'Blender《大城市场景》创建流程教学【英音中字】',
    //     work: false,
    //     courseType: 1,
    //     id: 5,
    //     children: [
    //       {
    //         id: 6,
    //         title: 'Blender《大城市场景》创建流程教学【英音中字】',
    //         work: false,
    //         courseType: 1,
    //       },
    //       {
    //         id: 7,
    //         title: 'Blender《大城市场景》创建流程教学【英音中字】',
    //         work: false,
    //         courseType: 1,
    //       },
    //       {
    //         id: 8,
    //         title: 'Blender《大城市场景》创建流程教学【英音中字】',
    //         work: false,
    //         courseType: 1,
    //       },
    //     ],
    //   },
    //   {
    //     id: 9,
    //     title: 'Blender《大城市场景》创建流程教学【英音中字】',
    //     work: false,
    //     courseType: 1,
    //   },
    // ],
  );
  const onTitleChange = async (record, name) => {
    // console.log(record, name);
    const response = await allGet({
      params: {
        version: 'pc1.0',
        mod: 'chapter',
        do: 'update',
        cid: record.cid,
        name,
        classid,
      },
    });
    if (response.success) {
      reload();
    }
    // const list = data.map((item) => {
    //   if (item.cid === record.cid) {
    //     item.name = name;
    //     return item;
    //   } else if (item.children) {
    //     const children = item.children.map((it) => {
    //       if (it.cid === record.cid) {
    //         it.name = name;
    //       }
    //       return it;
    //     });
    //     return {
    //       ...item,
    //       children,
    //     };
    //   } else {
    //     return item;
    //   }
    // });
    // setData(list);
  };
  const onLessonChange = async (lids, update, needReload = true) => {
    const response = await allGet({
      params: {
        classid,
        version: 'pc1.0',
        mod: 'lesson',
        do: 'update',
        lids,
        ...update,
      },
      paramsSerializer(params) {
        return qs.stringify(params);
      },
    });
    if (response.success && needReload) {
      reload();
    }
  };
  const onWorkChange = (lid, values) => {
    onLessonChange(
      lid,
      {
        ...values,
      },
      false,
    );
  };

  const onDelete = async (mod, key, record) => {
    // if (record.chapter) {
    //   const response = await allGet({
    //     params: {
    //       version: 'pc1.0',
    //       mod: 'chapter',
    //       do: 'deletelesson',
    //       cid: record.chapter,
    //       lids: [record.lid],
    //     },
    //   });
    //   if (response.success) {
    //     message.success('删除成功');
    //     reload();
    //   }
    // } else {
    const params = {
      version: 'pc1.0',
      mod,
      do: 'delete',
      classid,
    } as any;
    if (key === 'lids') {
      params.lids = record[key]?.join(',');
    } else {
      params[key] = record[key];
    }

    const response = await allGet({
      params,
    });
    if (response.success) {
      message.success('删除成功');
      reload();
    }
    // }
  };
  const onBatchDelete = async () => {
    if (!selectedRowKeys || !selectedRowKeys.length) {
      message.warning('请选择课时');
    } else {
      console.log(selectedRowKeys);
      // todo 批量删除
      Modal.confirm({
        title: '提示',
        content: '确定批量删除已选中的课时吗？',
        onOk() {
          onDelete('lesson', 'lids', { lids: selectedRowKeys });
        },
      });
    }
  };
  const addLessonToChapter = async (record, lids) => {
    const response = await allGet({
      params: {
        version: 'pc1.0',
        mod: 'chapter',
        do: 'addlesson',
        cid: record.cid,
        lids,
        classid,
      },
    });
    if (response.success) {
      reload();
    }
    return response.success as boolean;
  };
  const onSort = async (lid, index) => {
    const response = await allGet({
      params: {
        version: 'pc1.0',
        mod: 'lesson',
        do: 'move',
        lid,
        index,
        classid,
      },
    });
    if (response.success) {
      reload();
    }
  };
  const columns = [
    {
      title: '序号',
      dataIndex: '排序',
      key: '排序',
      align: 'center',
      className: styles.numberTd,
      width: 96,
      render: (_, record) => {
        if (record.lid !== undefined) return <span>{record.index}</span>;
        return <span>第 {record.displayorder} 章</span>;
      },
    },
    {
      title: '标题',
      dataIndex: 'name',
      key: 'name',
      render: (name, record) => {
        return isModal ? (
          name
        ) : (
          <Title
            value={name}
            maxWidth={520}
            onChange={(value) => {
              record.children
                ? onTitleChange(record, value)
                : onLessonChange(record.lid, { name: value });
            }}
          />
        );
      },
    },
    // {
    //   title: '',
    //   key: 'tjks',
    //   width: 186,
    //   hideInTable: isModal,
    //   render: (type, record) => {
    //     if (record.children) {
    //       return (
    //         <AddLesson
    //           chapterIndex={record?.displayorder}
    //           data={data.filter((item) => item.chapter === '0')}
    //           onSubmit={(lids) => addLessonToChapter(record, lids)}
    //         >
    //           <Button type="ghost" size="small">
    //             添加课时
    //           </Button>
    //         </AddLesson>
    //       );
    //     }
    //     return null;
    //   },
    // },
    {
      title: isModal ? '作业' : '有无作业',
      dataIndex: 'allowbusywork',
      key: 'allowbusywork',
      width: 156,
      render(text, record) {
        return (
          <Homework
            formType={isModal && record.children ? 'checkbox' : 'switch'}
            value={{ busywork: record.busywork, allowbusywork: text, reward: record.reward }}
            onOk={(value) => onWorkChange(record.lid, value)}
          />
        );
      },
    },
    {
      title: '课程类型',
      dataIndex: 'type',
      key: 'type',
      width: 186,
      hideInTable: isModal,
      render: (type, record) => {
        if (!record.children) {
          return (
            <Type
              value={{ type }}
              onChange={(update) => {
                onLessonChange(record.lid, update);
              }}
            />
          );
        }
        return null;
      },
    },
    {
      title: '操作',
      dataIndex: '操作',
      key: '操作',
      width: 157,
      align: 'center',
      hideInTable: isModal,
      render(_, record) {
        return (
          <div className={styles.handles}>
            {!record.children ? (
              <>
                <i
                  className={classnames([
                    styles.moveUp,
                    { [styles.disabled]: !Boolean(record.beforeIndex) },
                  ])}
                  onClick={() => record.beforeIndex && onSort(record.lid, record.beforeIndex)}
                />
                <i
                  className={classnames([
                    styles.moveDown,
                    { [styles.disabled]: !Boolean(record.afterIndex) },
                  ])}
                  onClick={() => record.afterIndex && onSort(record.lid, record.afterIndex)}
                />
                <Divider type="vertical" style={{ borderColor: '#43669C', margin: '0 18px' }} />
              </>
            ) : (
              <AddLesson
                chapterIndex={record?.displayorder}
                data={data.filter((item) => item.chapter === '0')}
                onSubmit={(lids) => addLessonToChapter(record, lids)}
                style={{ marginRight: 18 }}
              >
                <Button type="ghost" size="small" className="cg-ghost-button">
                  添加课时
                </Button>
              </AddLesson>
            )}

            <Popconfirm
              title={`是否要删除${record.children ? '章节' : '视频'}`}
              okText="删除"
              cancelText="取消"
              overlayClassName="c-tooltip"
              onConfirm={() => {
                if (record.children) {
                  onDelete('chapter', 'cid', record);
                } else {
                  onDelete('lesson', 'lid', record);
                }
              }}
              icon={
                <img
                  loading="lazy"
                  style={{ width: 18, float: 'left', marginTop: 2 }}
                  src={removeSrc}
                  alt=""
                />
              }
              cancelButtonProps={{
                style: {
                  background: '#7688A5',
                  color: '#fff',
                  border: 0,
                },
              }}
              okButtonProps={{
                style: {
                  background: '#FF5967',
                  color: '#fff',
                  border: 0,
                },
              }}
            >
              <a>
                <img loading="lazy" style={{ width: 24 }} src={removeSrc} alt="" />
              </a>
            </Popconfirm>
          </div>
        );
      },
    },
  ];
  useEffect(() => {
    setData(dataSource);
    // const expandedRowKeys = dataSource
    //   .filter((item) => item.children?.length > 0)
    //   .map(({ cid }) => cid);
    // setExpandedRowKeys(expandedRowKeys);
    // console.log(expandedRowKeys);
  }, [dataSource]);
  // useEffect(() => {
  //   if (document.querySelector('.ant-table-selection-column + th')) {
  //     document
  //       .querySelector('.ant-table-selection-column + th')
  //       ?.setAttribute('style', 'text-align: center');
  //     (document.querySelector('.ant-table-selection-column + th') as any).innerHTML = '序号';
  //   }
  // }, []);
  return (
    <div className={styles.container}>
      {!isModal && (
        <div className={styles.btns}>
          <Chapter reload={reload} dataSource={data} />
          <span>
            {/* <Button
              type="primary"
              style={{
                background: 'rgba(37, 77, 248, 0.3000)',
                borderColor: 'rgba(37, 77, 248, 1)',
              }}
            >
              批量设置课程类型
            </Button> */}
            <Button
              type="primary"
              className={styles['btn-delete']}
              disabled={!selectedRowKeys || !selectedRowKeys.length}
              onClick={onBatchDelete}
            >
              批量删除
            </Button>
          </span>
        </div>
      )}
      <Table
        rowSelection={
          isModal
            ? undefined
            : {
                columnWidth: 32,
                onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
                  // console.log(
                  //   `selectedRowKeys: ${selectedRowKeys}`,
                  //   'selectedRows: ',
                  //   selectedRows,
                  // );
                  setSelectedRowKeys(selectedRowKeys);
                },
                getCheckboxProps: (record) => {
                  return !!record.lid
                    ? {}
                    : {
                        style: {
                          display: 'none',
                        },
                        disabled: true,
                      };
                },
              }
        }
        locale={{
          emptyText: (
            <Empty
              text={
                (
                  <div>
                    <p>暂无内容</p>
                  </div>
                ) as any
              }
              style={{ margin: '100px auto' }}
            />
          ),
        }}
        columns={columns.filter((item) => !!!item.hideInTable)}
        rowClassName={(record) => `${record.cid ? 'c' : 'l'} ${record.chapter != '0' ? 'c0' : ''}`}
        className={styles.table}
        bordered={false}
        dataSource={calcIndex(data)}
        rowKey={(record) => record.lid || record.cid}
        pagination={false}
        loading={loading}
        scroll={isModal ? { y: '70vh' } : undefined}
        expandable={{
          columnTitle: <span>课时</span>,
          defaultExpandAllRows: true,
          expandedRowKeys: expandedRowKeys,
          onExpandedRowsChange: (expandedRows) => setExpandedRowKeys(expandedRows as any[]),
          expandIcon: ({ expanded, onExpand, record }) => {
            if (record.lid !== undefined) return null;
            return (
              <span style={{ position: 'absolute', left: -16, top: 18 }}>
                {record.children && record.children.length ? (
                  <img
                    style={{ width: 19, cursor: 'pointer', marginRight: 8 }}
                    src={expanded ? jtsrc : jt2src}
                    onClick={(e) => onExpand(record, e)}
                  />
                ) : (
                  <i style={{ width: 19, marginRight: 8 }} />
                )}
              </span>
            );
          },
        }}
      />
    </div>
  );
};
export default Index;
